package me.tuyou.jvm.reference;

import me.tuyou.jvm.reference.vo.MyObject;

import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;

/**
 * 虚引用测试
 * 对象如果只存在虚引用可达，在gc(minor gc和full gc)时会被回收
 * https://blog.csdn.net/baidu_22254181/article/details/82555485
 * 放入队列的是引用，值已经被gc回收
 * @Author tuyou_cd
 * @Date 2020/7/22 15:00
 */
public class WeakReferenceTest {

    public static void main(String[] args) throws InterruptedException {
        ReferenceQueue queue = new ReferenceQueue();
        WeakReference reference = new WeakReference(new MyObject("1"), queue);

        System.out.println("gc前，引用值：" + reference.get()); //not null
        System.out.println("gc前，是否加入已回收队列：" + reference.isEnqueued()); //false

        System.gc();
        Thread.sleep(1000); //延时1秒，等待gc完毕

        System.out.println("gc后，引用值：" + reference.get()); //null
        System.out.println("gc后，是否加入已回收队列：" + reference.isEnqueued());//true

        Reference ref = null;
        while((ref = queue.poll()) != null) {
            System.out.println("gc后，是否找到回收引用：" + (ref == reference)); //true
        }
    }
}
